package ebiz.buddhist.texts;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Toast;
import ebiz.buddhist.texts.network.NetworkUtil;



public class JiJangView extends Activity {
	ArrayAdapter<String> adspin;
	ArrayList<String> mList;
	ProgressDialog mProgress;
	SeekBar mSeekbar;
	MediaPlayer mPlayer;
	TelephonyManager mTelMan; //------- 통화시 mp3 play 중지 
	int mValue;
	Button mPlayBtn;
	boolean wasPlaying;
	boolean isMpCheck;
	boolean isDownCheck = false; 	 
	boolean mResumeAfterCall; //------- 통화시 mp3 play 중지 

	String compareStr;
	String mpPathStr;
	String RenameStr;
	String strMenuname="우리말 지장경";
	int menuNum;

	public String[] intentEx = {"jijang01.mp3","jijang02.mp3","jijang03.mp3","jijang04.mp3"
			,"jijang05.mp3","jijang06.mp3","jijang07.mp3","jijang08.mp3","jijang09.mp3",
			"jijang10.mp3","jijang11.mp3","jijang12.mp3","jijang13.mp3"};
	public String[] strUrl = {
			"file:///android_asset/jijang/jijang01.html","file:///android_asset/jijang/jijang02.html","file:///android_asset/jijang/jijang03.html",
			"file:///android_asset/jijang/jijang04.html","file:///android_asset/jijang/jijang05.html","file:///android_asset/jijang/jijang06.html",
			"file:///android_asset/jijang/jijang07.html","file:///android_asset/jijang/jijang08.html","file:///android_asset/jijang/jijang09.html",
			"file:///android_asset/jijang/jijang10.html","file:///android_asset/jijang/jijang11.html","file:///android_asset/jijang/jijang12.html",
			"file:///android_asset/jijang/jijang13.html"};
	public String[] strKorUrl = {
			"file:///android_asset/jijang/kor_jijang01.html","file:///android_asset/jijang/kor_jijang02.html","file:///android_asset/jijang/kor_jijang03.html",
			"file:///android_asset/jijang/kor_jijang04.html","file:///android_asset/jijang/kor_jijang05.html","file:///android_asset/jijang/kor_jijang06.html",
			"file:///android_asset/jijang/kor_jijang07.html","file:///android_asset/jijang/kor_jijang08.html","file:///android_asset/jijang/kor_jijang09.html",
			"file:///android_asset/jijang/kor_jijang10.html","file:///android_asset/jijang/kor_jijang11.html","file:///android_asset/jijang/kor_jijang12.html",
			"file:///android_asset/jijang/kor_jijang13.html"};
	ConnectivityManager cMgr;
	
	boolean mOmitChapter;
	String[] arJijang = {
			"지장경 목차",
			"제1품 도리천궁신통품",
			"제2품 분신집회품",
			"제3품 관중생업연품",
			"제4품 염부중생업감품",
			"제5품 지옥명호품",
			"제6품 여래찬탄품",
			"제7품 이익존망품",
			"제8품 염라왕중찬탄품",
			"제9품 칭불명호품",
			"제10품 교량포시공덕품",
			"제11품 지신호법품",
			"제12품 견문리익품",
			"제13품 촉루인천품",			
		};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.jijang);		
		
		 
		  
	   mList = new ArrayList<String>();
	   mPlayer = new MediaPlayer();
	   compareStr = revIntent();
	   RenameStr = mpReName(compareStr);
	 
	   arJijang[0] = "- " + RenameStr + " -";
	  Spinner spin = (Spinner)findViewById(R.id.jijangspinner);
		spin.setPrompt("목차");

			adspin = new ArrayAdapter<String>(this, 
					android.R.layout.simple_spinner_item, arJijang);
			adspin.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		  spin.setAdapter(adspin);
	      WebView webview = (WebView) findViewById(R.id.webkit);
	     
	      WebSettings ws = webview.getSettings();

	        ws.setJavaScriptEnabled(true);		// 잡스크립트실행여부
	        ws.setJavaScriptCanOpenWindowsAutomatically(true);
	        ws.setDomStorageEnabled(true);
	      
	      Uri u = getIntent().getData();
	      webview.loadUrl(u.toString());
	            
	     //------- 통화시 mp3 play 중지 
	      mTelMan = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
		  mTelMan.listen(mCallListener, PhoneStateListener.LISTEN_CALL_STATE);
		  //------- 통화시 mp3 play 중지 
		  mPlayBtn = (Button)findViewById(R.id.play);
		// 완료 리스너, 시크바 변경 리스너 등록
		  mPlayer.setOnCompletionListener(mOnComplete);
		  mPlayer.setOnSeekCompleteListener(mOnSeekComplete);		
		  mSeekbar = (SeekBar)findViewById(R.id.viewseekbar);
		  mSeekbar.setOnSeekBarChangeListener(mOnSeek);
		  mSeekbarHandler.sendEmptyMessageDelayed(0,200);
		  mpInit();			
		
		spin.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view, 
					int position, long id) {
				mOnSelect(position);
				
			}
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
	}
	public void CommAct(String exput,int position)
	{
		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(exput),
                this, JiJangView.class);
		intent.putExtra("TextIn",intentEx[position]);
		startActivity(intent);
	}
	public void mOnSelect(int pos)
	{
		switch(pos)
		{
		case 0:
		/*	finish();
			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("file:///android_asset/jijang01.html"),
	                this, JiJangView.class);
			intent.putExtra("TextIn","jijang01.mp3");
			startActivity(intent);*/
			break;
		case 1:
			finish();
			CommAct(strUrl[pos-1],pos-1);
			break;
		case 2:
			finish();
			CommAct(strUrl[pos-1],pos-1);
			break;
		case 3:
			finish();
			CommAct(strUrl[pos-1],pos-1);
			break;
		case 4:
			finish();
			CommAct(strUrl[pos-1],pos-1);
			break;
		case 5:
			finish();
			CommAct(strUrl[pos-1],pos-1);
			break;
		case 6:
			finish();
			CommAct(strUrl[pos-1],pos-1);
			break;
		case 7:
			finish();
			CommAct(strUrl[pos-1],pos-1);
			break;
		case 8:
			finish();
			CommAct(strUrl[pos-1],pos-1);
			break;
		case 9:
			finish();
			CommAct(strUrl[pos-1],pos-1);
			break;
		case 10:
			finish();
			CommAct(strUrl[pos-1],pos-1);
			break;
		case 11:
			finish();
			CommAct(strUrl[pos-1],pos-1);
			break;
		case 12:
			finish();
			CommAct(strUrl[pos-1],pos-1);
			break;
		case 13:
			finish();
			CommAct(strUrl[pos-1],pos-1);
			break;
		case 14:
			finish();
			CommAct(strUrl[pos-1],pos-1);
		}
	}
	 public void mpInit()
	   {
		   mpPathStr =  FileNameSearch(compareStr);
		// 첫 곡 읽기 및 준비
			if (LoadMedia(mpPathStr) == false) {
				mPlayBtn.setText(RenameStr + "다운");
				mSeekbar.setVisibility(View.GONE); // mp파일이 없을시 seekbar를 지운다
				isMpCheck = false;			
			}    
			else
			{			
				isMpCheck = true;
			}
	   }
	   
	   Handler mSeekbarHandler = new Handler() {
			public void handleMessage(Message msg) {
				if (mPlayer == null) return;
				if (mPlayer.isPlaying()) {
					mSeekbar.setProgress(mPlayer.getCurrentPosition());
				}
				mSeekbarHandler.sendEmptyMessageDelayed(0,200);
			}
		};
	// 재생 위치 이동
		SeekBar.OnSeekBarChangeListener mOnSeek = 
			new SeekBar.OnSeekBarChangeListener() {
			public void onProgressChanged(SeekBar seekBar, 
					int progress, boolean fromUser) {
				if (fromUser) {
					mPlayer.seekTo(progress);
				}
			}

			public void onStartTrackingTouch(SeekBar seekBar) {
				wasPlaying = mPlayer.isPlaying();
				if (wasPlaying) {
					mPlayer.pause();
				}
			}

			public void onStopTrackingTouch(SeekBar seekBar) {
			}
		};
		
		
	   public String mpReName(String str)
	   {
		   String strCompare = str;
		   if(strCompare.compareTo("jijang01.mp3")== 0)
			   strCompare = "제1품 도리천궁신통품";
		   if(strCompare.compareTo("jijang02.mp3")== 0)
			   strCompare = "제2품 분신집회품";
		   if(strCompare.compareTo("jijang03.mp3")== 0)
			   strCompare = "제3품 관중생업연품";
		   if(strCompare.compareTo("jijang04.mp3")== 0)
			   strCompare = "제4품 염부중생업감품";
		   if(strCompare.compareTo("jijang05.mp3")== 0)
			   strCompare = "제5품 지옥명호품";
		   if(strCompare.compareTo("jijang06.mp3")== 0)
			   strCompare = "제6품 여래찬탄품";
		   if(strCompare.compareTo("jijang07.mp3")== 0)
			   strCompare = "제7품 이익존망품";
		   if(strCompare.compareTo("jijang08.mp3")== 0)
			   strCompare = "제8품 염라왕중찬탄품";
		   if(strCompare.compareTo("jijang09.mp3")== 0)
			   strCompare = "제9품 칭불명호품";
		   if(strCompare.compareTo("jijang10.mp3")== 0)
			   strCompare = "제10품 교량포시공덕품";
		   if(strCompare.compareTo("jijang11.mp3")== 0)
			   strCompare = "제11품 지신호법품";
		   if(strCompare.compareTo("jijang12.mp3")== 0)
			   strCompare = "제12품 견문리익품";
		   if(strCompare.compareTo("jijang13.mp3")== 0)
			   strCompare = "제13품 촉루인천품";
		   return strCompare;
	   }
	   public void onDestroy() {
	       super.onDestroy();
	       if (mPlayer != null) {
	       	mPlayer.release();
	       	mPlayer = null;
	       }
			mTelMan.listen(mCallListener, PhoneStateListener.LISTEN_NONE);
	   }
	   public String FileNameSearch(String strPath)
		{
		    String path;
			File SDCardRoot = Environment.getExternalStorageDirectory(); 
	        File dir = new File(SDCardRoot + "/buddhist/");
			if(dir!=null) {
				File[] dirs = dir.listFiles();
				if(dirs!=null) {
					for(int i=0; i<dirs.length; i++) {
						
						if(dirs[i].getName().endsWith("mp3")) {
							path = dirs[i].getName();
							if(path.compareTo(strPath) == 0) 
								return dirs[i].getAbsolutePath();
							if(path.compareTo(strPath) == 0) 
								return dirs[i].getAbsolutePath();
						}
					}
				}
			}
			
			return  strPath;
		}
	   // 항상 준비 상태여야 한다.
	   boolean LoadMedia(String idx) {
			try {
				mPlayer.setDataSource(idx);
			} catch (IllegalArgumentException e) {
				return false;
			} catch (IllegalStateException e) {
				return false;
			} catch (IOException e) {
				return false;
			}
			if (Prepare() == false) {
				return false;
			}
			mSeekbar.setMax(mPlayer.getDuration());
			return true;
	   }
	   
	   boolean Prepare() {
			try {
				mPlayer.prepare();
			} catch (IllegalStateException e) {
				return false;
			} catch (IOException e) {
				return false;
			}
			return true;
	   }
	// 재생 완료되면 다음곡으로
	   MediaPlayer.OnCompletionListener mOnComplete = 
	   	new MediaPlayer.OnCompletionListener() {
			public void onCompletion(MediaPlayer arg0) {
				mPlayBtn.setText("Play");
			}
	   };
	   // 위치 이동 완료 처리
	   MediaPlayer.OnSeekCompleteListener mOnSeekComplete = 
	   	new MediaPlayer.OnSeekCompleteListener() {
			public void onSeekComplete(MediaPlayer mp) {
				if (wasPlaying) {
					mPlayer.start();
				}
			}
	   };
	   public String revIntent()
	   {
		   Intent intent = getIntent();
		   String text = intent.getStringExtra("TextIn");
		   return text;
	   }
	   public int SearchUrl()
	   {
		   int i;
		   for(i=0;i < 13;i++)
		   {
			   if(compareStr.compareTo(intentEx[i])==0)
				   break;
		   }
		   return i;
	   }
	   public boolean onCreateOptionsMenu(Menu menu) {
			super.onCreateOptionsMenu(menu);
			menu.add(0,1,0,strMenuname);
			return true;
		}
		public boolean onOptionsItemSelected(MenuItem item) {
			//switch (item.getItemId()) {
			switch (item.getItemId()) {
			case 1:			
				finish();
				int i = SearchUrl();
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(strKorUrl[i]),
		                this, kor_JijangView.class);
				intent.putExtra("TextIn",compareStr);
				startActivity(intent);
				return true;		
			}
			return false;
		}
	   public void mOnClick(View v) {
	   	switch (v.getId()) {
	       // 재생 및 일시 정지
	   	case R.id.play:
	   		if(isDownCheck == true)
	   		{
	   			finish();
	   			int i = SearchUrl();
	   			CommAct(strUrl[i],i);
	   		}
	   		if(isMpCheck == false)
	   		{
	   			cMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	   			String ext = Environment.getExternalStorageState();

	   		 	if (ext.equals(Environment.MEDIA_MOUNTED) == false) {
	   		 		Toast.makeText(this, "SD 카드가 반드시 필요합니다.", 1).show();
	   		 		break;
	   		 	}
	 		
	   			if (NetworkUtil.connectionPresent(cMgr)) { 	
	   				if(isDownCheck==false)
	   				{
	   					alertDown();
	   					mPlayBtn.setText("새로고침");
	   					isDownCheck = true;
	   				}
	   			} else {
	   				Toast.makeText(JiJangView.this, getString(R.string.networkerror), Toast.LENGTH_LONG).show();
	   			}
	   		}
	   		else
	   		{
				if (mPlayer.isPlaying() == false) {
					mPlayer.start();
					mPlayBtn.setText("Pause");
				} else {
					mPlayer.pause();
					mPlayBtn.setText("Play");
				}
	   		}
	   		break;
	   	  	}
	   }
		void doDownload() {
			new AccumulateTask().execute(100);
		}
		void alertDown()
		{
			new AlertDialog.Builder(JiJangView.this)
			.setTitle("질문")
			.setMessage("다운로드 하시겠습니까?")
			.setPositiveButton("예", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {			
					doDownload();				
				}
			})				
			.setNegativeButton("아니오", null)
			.show();
		}
		  //------- 통화시 mp3 play 중지 
		PhoneStateListener mCallListener = new PhoneStateListener() {
			public void onCallStateChanged (int state, String incomingNumber) {
				switch (state) {
				case TelephonyManager.CALL_STATE_IDLE:
					if (mResumeAfterCall) {
					/*	
						mTextCall.postDelayed(new Runnable() {
							public void run() {
								mPlayer.start();
							}
						}, 3000);
					*/	
						mPlayer.start();
					}
					break;
				case TelephonyManager.CALL_STATE_RINGING:
					// 전화오면 즉시 재생 중지
					if (mPlayer.isPlaying()) {
						mPlayer.pause();
						mResumeAfterCall = true;
					} else {
						mResumeAfterCall = false;
					}
					break;
				case TelephonyManager.CALL_STATE_OFFHOOK:
					break;
				}
			}
		};
		  //------- 통화시 mp3 play 중지 
	class AccumulateTask extends AsyncTask<Integer, Integer, Integer> {
		protected void onPreExecute() {
			mValue = 0;
			mProgress = new ProgressDialog(JiJangView.this);
			mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setTitle("다운로드");
			mProgress.setMessage("다운중...");
			mProgress.setCancelable(false);
			mProgress.setProgress(0);
			mProgress.setButton("중지", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					cancel(true);
				}
			});
			mProgress.show();
		}
		
		protected Integer doInBackground(Integer... arg0) {
			while (isCancelled() == false) { 
			//	mValue++;
				if (mValue <= 100) {
					publishProgress(mValue);
				} else {
					//String str = mValue + " ";
					//Toast.makeText(maincon, str, Toast.LENGTH_SHORT).show();
					break;
				}
				try { 
					 	//String urlstr = "http://sekisuri.cafe24.com/buddhist/music/";
						String urlstr = "https://sites.google.com/site/sekisuri/";
						String mpfilestr = urlstr + compareStr;
					    URL url = new URL(mpfilestr);
					   
				        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();   
				        urlConnection.setRequestMethod("GET");   
				        urlConnection.setDoOutput(true);   
				        urlConnection.connect();   
				        int totalSize = urlConnection.getContentLength();   
				        int downloadedSize = 0;  
				        if(totalSize <= 0)
				        {
				        	 mValue = 101;					        	
					         Thread.sleep(50); 
				        }
				        else
				        {
					        File SDCardRoot = Environment.getExternalStorageDirectory(); 
					        File path = new File(SDCardRoot + "/buddhist/");
					        if(! path.isDirectory()) {
					                path.mkdirs();
					          }
					        File file = new File(path, compareStr);   
					        FileOutputStream fileOutput = new FileOutputStream(file);   
					        InputStream inputStream = urlConnection.getInputStream();   
					       
			//		        int totalSize = urlConnection.getContentLength();   
			//		        int downloadedSize = 0;   
				                
					        byte[] buffer = new byte[1024];   
					        int bufferLength = 0;
					         while ( (bufferLength = inputStream.read(buffer)) > 0 ) {   
					         fileOutput.write(buffer, 0, bufferLength);   
					         downloadedSize += bufferLength;   
					             updateProgress(downloadedSize, totalSize); 
					         }
					         mValue = 101;
					         fileOutput.close();  
					         Thread.sleep(50); 
				        }
				       
				         } catch (InterruptedException e) {
				          e.printStackTrace();
				         }catch (MalformedURLException e) {   
				          e.printStackTrace();   
				         } catch (IOException e) {   
				          e.printStackTrace();   
				         }

				       }

			return mValue;
		}
			 public void updateProgress(int downloadedSize, int totalSize) {
				  // TODO Auto-generated method stub
				 mProgress.setProgress(100 * downloadedSize/totalSize); 
				 }

	    protected void onProgressUpdate(Integer... progress) {         
	    	mProgress.setProgress(progress[0]);     
	    //	mText.setText(Integer.toString(progress[0]));     
	    }
	    
	    protected void onPostExecute(Integer result) { 
	    	mProgress.dismiss();
	    }
	    
	    protected void onCancelled() {
			mProgress.dismiss();
	    }
	}
}
